package com.yly.doctorapp.ui.usercenter;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.yly.doctorapp.R;
import com.yly.doctorapp.base.BaseActivity;
import com.yly.doctorapp.base.DoctorAppApplication;
import com.yly.doctorapp.bean.ResponsDataBean;
import com.yly.doctorapp.constant.Configution;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.x;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ForgetPasswordActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_phone)
    EditText tvPhone;
    @BindView(R.id.v_phone)
    View vPhone;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.tv_getcode)
    TextView tvGetcode;
    @BindView(R.id.v_code)
    View vCode;
    @BindView(R.id.edit_password)
    EditText editPassword;
    @BindView(R.id.iv_password)
    ImageView ivPassword;
    @BindView(R.id.v_password)
    View vPassword;
    @BindView(R.id.edit_surepassword)
    EditText editSurepassword;
    @BindView(R.id.iv_passwords)
    ImageView ivPasswords;
    @BindView(R.id.v_surepassword)
    View vSurepassword;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_password)
    TextView tvPassword;
    @BindView(R.id.tv_passwords)
    TextView tvPasswords;
    private String type = "";

    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_forgetpassword;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        type = getIntent().getStringExtra("type");
        if (type.equals("0")) {
            tvTitle.setText("忘记密码");
            tvPassword.setText("确认密码");
            editSurepassword.setHint("请再次输入确认密码");
            tvPasswords.setText("输入密码");
            editPassword.setHint("请输入密码");
            tvPhone.setEnabled(true);
            tvPhone.setFocusable(true);
            tvPhone.setFocusableInTouchMode(true);
        } else {
            tvTitle.setText("修改密码");
            tvPassword.setText("新密码");
            editSurepassword.setHint("请输入新密码");
            tvPasswords.setText("原密码");
            editPassword.setHint("请输入原密码");
            tvPhone.setEnabled(false);
            tvPhone.setFocusable(false);
            tvPhone.setFocusableInTouchMode(false);
        }
        tvPhone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    vPhone.setBackgroundColor(0xffa0524b);
                    vCode.setBackgroundColor(0xffcccccc);
                    vPassword.setBackgroundColor(0xffcccccc);
                    vSurepassword.setBackgroundColor(0xffcccccc);
                }
            }
        });
        editCode.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    vPhone.setBackgroundColor(0xffcccccc);
                    vCode.setBackgroundColor(0xffa0524b);
                    vPassword.setBackgroundColor(0xffcccccc);
                    vSurepassword.setBackgroundColor(0xffcccccc);
                }
            }
        });
        editPassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    vPhone.setBackgroundColor(0xffcccccc);
                    vCode.setBackgroundColor(0xffcccccc);
                    vPassword.setBackgroundColor(0xffa0524b);
                    vSurepassword.setBackgroundColor(0xffcccccc);
                }
            }
        });
        editSurepassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    vPhone.setBackgroundColor(0xffcccccc);
                    vCode.setBackgroundColor(0xffcccccc);
                    vPassword.setBackgroundColor(0xffcccccc);
                    vSurepassword.setBackgroundColor(0xffa0524b);
                }
            }
        });
        tvPhone.setText(getIntent().getStringExtra("phone"));
    }

    @Override
    protected void initData() {
        if (!StringUtils.isEmpty(getIntent().getStringExtra("phone"))) {
            tvPhone.setText(getIntent().getStringExtra("phone"));
        }
    }

    private int passwordCount = 0;
    private int surePasswordCount = 0;

    @OnClick({R.id.iv_back, R.id.tv_getcode, R.id.iv_password, R.id.iv_passwords, R.id.tv_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_getcode:
                if (StringUtils.isEmpty(tvPhone.getText().toString())) {
                    ToastUtils.show(getApplicationContext(), "手机不能为空", 100);
                    return;
                }
                tvGetcode.setEnabled(false);
                initSendMessage(tvPhone.getText().toString());
                break;
            case R.id.iv_password:
                if ((passwordCount % 2) == 0) {
                    ivPassword.setImageResource(R.mipmap.passwordshow);
                    editPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    ivPassword.setImageResource(R.mipmap.passwordnoshow);
                    editPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                passwordCount++;
                break;
            case R.id.iv_passwords:
                if ((surePasswordCount % 2) == 0) {
                    ivPasswords.setImageResource(R.mipmap.passwordshow);
                    editSurepassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    ivPasswords.setImageResource(R.mipmap.passwordnoshow);
                    editSurepassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                surePasswordCount++;
                break;
            case R.id.tv_sure:
                if (StringUtils.isEmpty(tvPhone.getText().toString())) {
                    ToastUtils.show(getApplicationContext(), "手机不能为空", 100);
                    return;
                }
                if (tvPhone.getText().toString().length() != 11) {
                    ToastUtils.show(getApplicationContext(), "请输入正确的手机号码", 100);
                    return;
                }
                if (StringUtils.isEmpty(editCode.getText().toString())) {
                    ToastUtils.show(getApplicationContext(), "请输入验证码", 100);
                    return;
                }
                if (StringUtils.isEmpty(editPassword.getText().toString())) {
                    ToastUtils.show(getApplicationContext(), "请输入密码", 100);
                    return;
                }
                if (StringUtils.isEmpty(editSurepassword.getText().toString())) {
                    if (type.equals("0")) {
                        ToastUtils.show(getApplicationContext(), "请输入新密码", 100);
                    } else {
                        ToastUtils.show(getApplicationContext(), "请输入确认密码", 100);
                    }
                    return;
                }

                if (type.equals("0")){
                    if (!editPassword.getText().toString().equals(editSurepassword.getText().toString())){
                        ToastUtils.show(getApplicationContext(), "两次输入不一样", 100);
                        return;
                    }
                }

                if (null != DoctorAppApplication.mUserBean) {
                    initChangePassword(tvPhone.getText().toString(), DoctorAppApplication.mUserBean.getDoctorid() + "", editCode.getText().toString(), editPassword.getText().toString(), editSurepassword.getText().toString(), type);
                } else {
                    initChangePassword(tvPhone.getText().toString(), "", editCode.getText().toString(), editPassword.getText().toString(), editSurepassword.getText().toString(), type);
                }
                break;
        }
    }

    private void initSendMessage(String phone) {
        RequestParams params = new RequestParams(Configution.HOST + Configution.SENDMESSAGE);
        params.addBodyParameter("telephone", phone);
        params.addBodyParameter("type", "4");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtil.d(result);
                if (!StringUtils.isEmpty(result)) {
                    ResponsDataBean responsDataBean = JSON.parseObject(result, ResponsDataBean.class);
                    if (responsDataBean.getCode().equals("1000")) {
                        showCounter();
                    }
                    ToastUtils.show(getApplicationContext(), responsDataBean.getMsg(), 100);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtils.show(getApplicationContext(), "网络连接失败", 100);
                tvGetcode.setEnabled(true);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void initChangePassword(String telephone, String doctorid, String verCode, String pwd, String newPwd, String type) {
        RequestParams params = null;
        if (type.equals("0")) {
            params = new RequestParams(Configution.HOST + Configution.FORGETPASSWORD);
            params.addBodyParameter("telephone", telephone);
            params.addBodyParameter("verCode", verCode);
            params.addBodyParameter("pwd", pwd);
            params.addBodyParameter("rePwd", newPwd);
        } else {
            params = new RequestParams(Configution.HOST + Configution.CHANGEPASSWORD);
            params.addBodyParameter("telephone", telephone);
            params.addBodyParameter("doctorid", doctorid);
            params.addBodyParameter("verCode", verCode);
            params.addBodyParameter("pwd", pwd);
            params.addBodyParameter("newPwd", newPwd);
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtil.d(result);
                if (!StringUtils.isEmpty(result)) {
                    ResponsDataBean responsDataBean = JSON.parseObject(result, ResponsDataBean.class);
                    if (responsDataBean.getCode().equals("1000")) {
                        AppManager.getAppManager().finishAllActivity();
                        Intent mIntent = new Intent(ForgetPasswordActivity.this, LoginActivity.class);
                        startActivity(mIntent);
                        finish();
                    }else {
                        ToastUtils.show(getApplicationContext(), responsDataBean.getMsg(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtils.show(getApplicationContext(), "网络连接失败", 100);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    int count = 120;
    private Thread mThread;
    private boolean isRunnig = true;

    private void showCounter() {
        if (null != mThread) {
            mThread.interrupt();
            mThread = null;
        }
        isRunnig = true;
        mThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (isRunnig) {
                    try {
                        Thread.sleep(1000);
                        if (count > 0) {
                            count--;
                            Message message = new Message();
                            message.what = 0;
                            message.arg1 = count;
                            mHandler.sendMessage(message);
                        } else {
                            mHandler.sendEmptyMessage(1);
                            isRunnig = false;
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (UnsupportedOperationException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        mThread.start();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    tvGetcode.setText(String.valueOf(msg.arg1) + "S");
                    break;
                case 1:
                    tvGetcode.setText("获取验证码");
                    break;
            }
        }
    };
}
